#=
测试高斯积分
=#


include("../src/lgvmary.jl")
using ..lgvmary

using Symbolics


#=
∫ e^{-x^2} dx = √π
∫ x^{2n} e^{-0.5ax^2} dx = (2n-1)!! sqrt(2π/a) / a^n 
n=1 a=2: √π/2
∫ x^{2} e^{-x^2} dx / ∫ e^{-x^2} dx = 1/2
#
integral from -inf to inf x^2 e^{-x^2 + i*x} dx = √π/(4*e^{1/4}) ≈ 0.345097
int e^{-x^2 + i*x}  from -inf to inf = √π/e^{1/4}
∫ x^{2} e^{-x^2+x*im} dx / ∫ e^{-x^2+x*im} dx = 1/4

#
S = x^2 - x*im
∂S/∂x = 2x - im
0点 x = im/2由这个邻域生成thimble

S = x^2 - x*im + log(x)
∂S/∂x = 2x - im + 1/x
0点 x = i, -im/2由这个邻域生成thimble
=#

using Plots


function run(plt)
    x, imagv, S = fake_action()
    O = x^2*exp(S)
    ∂S_∂x = Symbolics.derivative(S, x)
    println(∂S_∂x)

    #三个解
    #x = -0.69769 - 0.375713 i
    #x = 0.182357 + 0.0414223 i
    #0.515333 + 0.534291 i

    xc = [-0.69769-0.375713im, 0.182357+0.0414223im, 0.515333+0.534291im]
    l1 = [100, 155, 84]
    l2 = [64, 200, 100]
    for idx in 1:1:3
        x0 = xc[idx]

        xvalt = []
        xval = x0 - 1e-6
        push!(xvalt, xval)
        for _ in Base.OneTo(l1[idx])
            xdot = Symbolics.value(substitute(∂S_∂x, Dict(x=>xval, imagv=>0.0+1.0im)))
            xdot = adjoint(xdot)
            xval = xval + xdot*0.1
            #println(xdot, " ", xval)
            push!(xvalt, xval)
        end
        xval = x0 + 1e-6
        for _ in Base.OneTo(l2[idx])
            xdot = Symbolics.value(substitute(∂S_∂x, Dict(x=>xval, imagv=>0.0+1.0im)))
            xdot = adjoint(xdot)
            xval = xval + xdot*0.1
            #println(xdot, " ", xval)
            push!(xvalt, xval)
        end
        scatter!(plt, real.(xvalt), imag.(xvalt))
    end
    #x0 = im
#
    #xval = x0 - 1e-6
    #xvalt = []
    ##push!(xvalt, xval)
    #for _ in Base.OneTo(100)
    #    xdot = Symbolics.value(substitute(∂S_∂x, Dict(x=>xval, imagv=>0.0+1.0im)))
    #    xdot = adjoint(xdot)
    #    xval = xval + xdot*0.1
    #    #println(xdot, " ", xval)
    #    push!(xvalt, xval)
    #end
    #xval = x0 + 1e-6
    #for _ in Base.OneTo(100)
    #    xdot = Symbolics.value(substitute(∂S_∂x, Dict(x=>xval, imagv=>0.0+1.0im)))
    #    xdot = adjoint(xdot)
    #    xval = xval + xdot*0.1
    #    #println(xdot, " ", xval)
    #    push!(xvalt, xval)
    #end
    #scatter!(plt, real.(xvalt), imag.(xvalt))
    xlims!(-1.1, 1.1)
    ylims!(-0.8, 0.8)
    savefig("test.png")
end



function run2(plt)
    x, imagv, S = fake_action()
    O = x^2*exp(S)
    ∂S_∂x = Symbolics.derivative(S, x)
    #三个解
    #x = -0.69769 - 0.375713 i
    #x = 0.182357 + 0.0414223 i
    #0.515333 + 0.534291 i

    xvalt = []
    for rv in range(-1.1, stop=1.1, length=100)
        cv, _ = inv_Morse(S, ∂S_∂x, x, rv, [imagv], [0.0+1.0im]; T=1.0)
        push!(xvalt, cv)
    end

    plot!(plt, real.(xvalt), imag.(xvalt), linestyle=:dash, lw=5)
    xlims!(-1.1, 1.1)
    ylims!(-0.8, 0.8)
    savefig("test2.png")
end

plt = plot()
run(plt)
run2(plt)
